import React from 'react';
import {withRouter} from 'react-router-dom';
import {Form, Input, Button, Row, Col} from 'antd';

import {validatorPhone, validatorCode, hasErrors} from '@/common/Validator';
import {formItemLayout} from '@/common/FormLayout';
import prefixSelector from '../Common/prefixSelector';

const FormItem = Form.Item;

@withRouter class GetCode extends React.Component {
  state = {
    sendSecondLast: 0,
    isSendedOnce: false,
    buttonLoading: false, // 按钮加载中
    sendLoading: false, // 发送验证码中
  };
  timerID = null;
  componentDidMount () {
    this.props.form.validateFields ();
  }
  handleSubmit = e => {
    e.preventDefault ();
    const self = this;
    const {buttonLoading} = this.state;
    const {history, location} = this.props;
    if (buttonLoading) {
      return;
    }
    this.props.form.validateFields ((err, values) => {
      if (!err) {
        console.log ('Received values of form: ', values);
        
        self.setState ({
          buttonLoading: true,
        });
        setTimeout (() => {
          // self.props.nextClick(1);
          this.setState ({
            buttonLoading: false,
          });
          history.replace (`${location.pathname}?step=1`);
        }, 1000);
        // registerApi (values)
        //   .then (result => {
        //     console.log ('result', result);
        //   })
        //   .catch (() => {
        //     self.isRegisterIng = false;
        //     message.error ('系统繁忙，请稍后重试！');
        //   });
      }
    });
  };
  sendCodeClick = () => {
    if (this.state.sendLoading) {
      return;
    }
    this.setState ({
      sendLoading: true,
    });
    setTimeout (() => {
      this.setState ({
        sendSecondLast: 60,
        sendLoading: false,
      });

      this.timerID = setInterval (() => {
        this.setState ({
          sendSecondLast: this.state.sendSecondLast - 1,
        });
        if (this.state.sendSecondLast === 0) {
          clearInterval (this.timerID);
          this.setState ({
            isSendedOnce: true,
          });
        }
      }, 1000);
    }, 1000);
  };
  render () {
    const {
      sendSecondLast,
      isSendedOnce,
      buttonLoading,
      sendLoading,
    } = this.state;
    const {
      getFieldDecorator,
      isFieldTouched,
      getFieldError,
      getFieldsError,
    } = this.props.form;

    const phoneError = isFieldTouched ('phone') && getFieldError ('phone');
    const codeError = isFieldTouched ('code') && getFieldError ('code');

    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem
          {...formItemLayout}
          label="手机号"
          validateStatus={phoneError ? 'error' : ''}
          help={phoneError || ''}
        >
          {getFieldDecorator ('phone', {
            rules: [
              {
                required: true,
                message: '请输入手机号码!',
              },
              {
                validator: validatorPhone,
              },
            ],
          }) (
            <Input
              addonBefore={prefixSelector (getFieldDecorator)}
              style={{
                width: '100%',
              }}
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="验证码"
          validateStatus={codeError ? 'error' : ''}
          help={codeError || ''}
        >
          <Row gutter={8}>
            <Col span={14}>
              {getFieldDecorator ('code', {
                rules: [
                  {
                    required: true,
                    message: '请输入验证码!',
                  },
                  {
                    validator: validatorCode,
                  },
                ],
              }) (<Input />)}
            </Col>
            <Col span={10}>
              <Button
                className="login-form-button"
                type="primary"
                onClick={this.sendCodeClick}
                disabled={
                  getFieldError ('phone') || sendSecondLast > 0 ? true : false
                }
                loading={sendLoading}
              >
                {sendSecondLast > 0
                  ? `${sendSecondLast}s后重新发送`
                  : isSendedOnce ? '再次发送' : '发送验证码'}
              </Button>
            </Col>
          </Row>
        </FormItem>
        <FormItem className="form-center-button">
          <Button
            type="primary"
            disabled={hasErrors (getFieldsError ())}
            htmlType="submit"
            loading={buttonLoading}
          >
            确定
          </Button>
        </FormItem>
      </Form>
    );
  }
}

export default Form.create () (GetCode);
